<template>
  <div class="submit-content">
    <slot name="title"></slot>
    <el-form
      :model="submitData"
      ref="submitData"
      :inline="formData.inline"
      :label-width="formData.labelWidth"
      class="demo-submitData"
    >
      <div v-for="item in form.list" :key="item.key">
        <el-form-item
          v-if="isShow(item.associatedField)"
          :label="item.label"
          :prop="item.key"
          :rules="item.rules"
          :required="item.required"
        >
          <el-input
            v-if="item.type === 'INPUT'"
            v-model="submitData[item.key]"
            :type="item.inputType || 'text'"
            :placeholder="item.placeholder || `请输入${item.label}`"
            :style="item.style || {}"
            :disabled="
              typeof item.disabled === 'function'
                ? item.disabled()
                : item.disabled
            "
            @change="
              (e) => {
                handleInputChange(e, item)
              }
            "
          ></el-input>
          <el-select
            v-model="submitData[item.key]"
            :placeholder="item.placeholder || `请输入${item.label}`"
            v-if="item.type === 'SELECT'"
            :style="item.style || {}"
          >
            <el-option
              v-for="list in item.list.length ? item.list : item.list()"
              :key="list[(item.props && item.props.value) || 'value']"
              :label="list[(item.props && item.props.label) || 'label']"
              :value="list[(item.props && item.props.value) || 'value']"
            ></el-option>
          </el-select>
          <div v-if="item.type === 'UPLOAD'">
            <image-upload
              :submitData="submitData"
              :data="item"
              @handleSuccess="handleSuccess"
              @handleRemove="handleRemove"
            ></image-upload>
            <el-input v-show="false" v-model="submitData[item.key]"></el-input>
            <div
              class="note"
              v-if="item.note"
              style="font-size: 12px; color: #909399;"
            >
              {{ item.note }}
            </div>
            <img v-if="item.tempUrl" :src="item.tempUrl" />
            <temp-html v-if="item.tempHtml" :render="item.tempHtml"></temp-html>
          </div>
          <el-cascader
            :placeholder="`请选择${item.label}`"
            v-if="item.type === 'CASCADER'"
            v-model="submitData[item.key]"
            :options="item.list.length ? item.list : item.list()"
            :props="item.props"
            @change="
              (e) => {
                handleChange(e, item.list.length ? item.list : item.list(), item)
              }
            "
            clearable
          ></el-cascader>
          <amap-map
            :areaName="areaName"
            v-if="item.type === 'AMAPMAP'"
            ref="maps"
            :inputStyle="{ width: '350px' }"
            :placeholder="item.label"
            :address.sync="submitData[item.key]"
            :getPoit="
              (data) => {
                getPoit(item.keyLng, item.keyLat, item.key, data)
              }
            "
            :init-center="[submitData[item.keyLng], submitData[item.keyLat]]"
          />
          <el-row
            v-if="!item.type && item.children"
            :style="item.style || style"
          >
            <el-col
              v-for="child in item.children"
              :span="24 / item.children.length"
              :key="child.key"
              class="child-item"
            >
              <el-form-item
                :key="child.key"
                :prop="child.key"
                :rules="child.rules"
              >
                <el-cascader
                  :placeholder="`请选择${child.label}`"
                  v-if="child.type === 'CASCADER'"
                  v-model="submitData[child.key]"
                  :options="child.list()"
                  :props="child.props"
                  @change="
                    (e) => {
                      handleChange(e, child.list())
                    }
                  "
                  clearable
                ></el-cascader>

                <el-input
                  :placeholder="`请输入${child.label}`"
                  v-if="child.type === 'INPUT'"
                  clearable
                  v-model="submitData[child.key]"
                  @change="
                    (e) => {
                      handleInputChange(e, child.trigger)
                    }
                  "
                >
                  <el-button
                    slot="append"
                    v-if="child.icon"
                    :icon="child.icon.name"
                    @click="
                      (e) => {
                        handlePoit(e, submitData[child.key])
                      }
                    "
                  ></el-button>
                </el-input>

                <div v-if="child.type === 'UPLOAD'">
                  <image-upload
                    :submitData="submitData"
                    :data="child"
                    @handleSuccess="handleSuccess"
                    @handleRemove="handleRemove"
                  ></image-upload>
                  <el-input
                    v-show="false"
                    v-model="submitData[child.key]"
                  ></el-input>
                  <div
                    class="note"
                    v-if="child.note"
                    style="font-size: 12px; color: #909399;"
                  >
                    {{ child.note }}
                  </div>
                  <img v-if="child.tempUrl" :src="child.tempUrl" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="item.type === 'div'" :style="item.style">
            {{ item.text }}
          </div>
          <el-date-picker
            v-if="item.type === 'DATE'"
            :format="item.format"
            v-model="submitData[item.key]"
            :type="item.dateType || 'date'"
            :value-format="item.valueFormat || item.format"
            :placeholder="`请选择${item.label}`"
            start-placeholder="请选择开始日期"
            end-placeholder="请选择结束日期"
            @change="
              (e) => {
                handleTimeSelect(e, item)
              }
            "
          ></el-date-picker>
          <el-radio-group
            v-model="submitData[item.key]"
            v-if="item.type === 'RADIO'"
          >
            <el-radio
              v-for="radio in item.list.length ? item.list : item.list()"
              :key="radio.value"
              :label="radio.value"
            >
              {{ radio.lable }}
              <span class="note">{{ radio.note }}</span>
            </el-radio>
          </el-radio-group>
          <div
            class="title-content"
            v-if="item.type === 'TITLE'"
            :style="{ left: `-${formData.labelWidth}` }"
          >
            {{ item.text }}
            <span class="note">{{ item.note }}</span>
          </div>
          <el-input-number
            style="width: 350px;"
            v-if="item.type === 'INPUTNUMBER'"
            :placeholder="`请输入${item.label}`"
            v-model="submitData[item.key]"
            :precision="item.precision"
            :controls="false"
            clearable
          ></el-input-number>
          <bank-type
            v-if="item.type === 'BANK'"
            ref="bank"
            :placeholder="item.label"
            :inputStyle="{ width: '350px' }"
            :bank.sync="submitData[item.keyBank]"
            :bankBranch.sync="submitData[item.keyZhi]"
          ></bank-type>
        </el-form-item>

        <el-form-item v-if="isOption">
          <slot name="buttons"></slot>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
<script>
import AmapMap from '@/components/AmapMap'
import imageUpload from '@/components/imageUpload'
import TempHtml from '@/components/TempHtml'
import BankType from '@/components/BankType'

export default {
  name: 'BaseForm',
  components: {
    AmapMap,
    imageUpload,
    TempHtml,
    BankType,
  },
  props: {
    submitData: {
      type: Object,
      default: () => ({}),
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
    pot: {
      type: String,
      default: () => '',
    },
    add: {
      type: Object,
      default: () => ({}),
    },
    isOption: {
      type: Boolean,
      default: () => true,
    },
    time: {
      type: Number,
      default: () => 60,
    },
  },
  data() {
    return {
      imageUrl: '',
      address: '',
      areaName: '',
      style: {
        width: '700px',
      },
      useless: '',
      form:{
        list: []
      },
    }
  },
  created() {},
  watch: {
    someKey(value) {
      let submitData = { ...this.submitData, ...this.add }
      if (!value) {
        submitData = {}
      }
      this.$emit('update:submitData', submitData)
    },
    formData: {
      handler(newName) {
        this.form =  _.cloneDeep(newName)
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    someKey() {
      if (this.pot) {
        return this.submitData[this.pot]
      } else {
        return this.useless
      }
    },
  },
  methods: {
    handleTry(fun) {
      return fun()
    },
    //监听队列回掉
    handleAddFun() {},
    handleTimeSelect(e, { dateType, setKeys }) {
      let arr = ['daterange']
      if (arr.includes(dateType)) {
        setKeys.forEach((key, ind) => {
          this.submitData[key] = e[ind]
        })
      }
    },
    handleChange(e, list, { key, setKey }) {
      if (setKey && e.length) {
        setKey.forEach((val, ind) => {
          this.submitData[val] = e[ind]
        })
      } else if (key) {
        delete this.submitData[key]
      }
      let address = this.handleSelect(e, list)
      this.areaName = address.join('')
    },
    isShow(key) {
      if (typeof key === 'string') {
        return this.submitData[key]
      } else if (typeof key === 'function') {
        return key()
      } else {
        return true
      }
    },
    handleSelect(e, list, address = []) {
      for (let i = 0; i < list.length; i++) {
        let { area_name, area_code, children } = list[i]
        let _find = e.includes(area_code)
        if (_find) {
          address.push(area_name)
          if (children && children.length) {
            this.handleSelect(e, children, address)
          }
          break
        }
      }
      return address
    },
    handlePoit(e, value) {
      let { areaName } = this
      this.address = areaName + (value || '')
      // this.$nextTick(() => {
      //   this.$refs.maps[0].autoInput(value, true);
      // });
    },
    handleInputChange(e, trigger) {
      switch (trigger) {
        case 'getYX':
          this.handlePoit(null, e)
          break
        default:
          {
            let { on } = trigger
            if (
              on &&
              Object.prototype.toString.call(on) === '[object Function]'
            ) {
              on(e)
            }
          }

          break
      }
    },
    handleSuccess({ obj, data }) {
      let submitData = { ...this.submitData, ...obj }
      this.$emit('update:submitData', submitData);
      this.$emit('uploadImgChange', { obj, data })
    },
    async submitForm() {
      return new Promise((resolve) => {
        this.$refs.submitData.validate((valid) => {
          resolve(valid)
        })
      })
    },
    handleRemove({ key }) {
      let pot = key.split('_')[0]
      let submitData = { ...this.submitData }
      for (let k in submitData) {
        if (k.includes(pot)) {
          delete submitData[k]
        }
      }
      this.$emit('update:submitData', submitData)
    },
    find() {},
    //初始化自动填充，后期再补吧
    getPoit(keyLng, keyLat, key, { lng, lat, address }) {
      this.submitData[keyLng] = lng
      this.submitData[keyLat] = lat
      this.submitData[key] = address
    },
  },
}
</script>
<style lang="less">
.demo-submitData {
  .child-item {
    padding-right: 10px;
  }
  .el-input__inner,
  .el-cascader,
  .el-select {
    max-width: 350px;
    width: 100%;
    text-align: left;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .el-date-editor {
    width: 350px;
  }
  .note {
    color: #909399;
    font-size: 12px;
    margin-left: 5px;
    line-height: 24px;
  }
  .title-content {
    position: relative;
  }
  .el-upload {
    overflow: inherit !important;
  }
  .remove {
    font-size: 24px;
    position: absolute;
    color: #bfbaba;
    right: 0;
    top: 0;
    transform: translate(50%, -50%);
    &:hover {
      color: #409eff;
    }
  }
}
</style>
